package com.qf.cloud2204.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Filter;

@Component
public class TestZuulFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;  // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 3;  // 过滤器的序号，越小的先执行
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 记录请求的起始时间戳
        long start = System.currentTimeMillis();



//        System.out.println("===============");
        // 检查请求头中是否有token

        RequestContext currentContext = RequestContext.getCurrentContext();
        currentContext.set("time-start",start);  // 把起始时间戳存入 currentContext对象


        HttpServletRequest request = currentContext.getRequest();

        String token = request.getHeader("token");

        if (token==null||"".equals(token)){
            // 让请求就此打住，不要再给后面的微服务发送了
            currentContext.setSendZuulResponse(false);

            // 获取respons对象
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.getWriter().println("no token");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return null;
    }
}
